package com.bigfans.framework.plugins;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.bigfans.framework.Applications;
import com.bigfans.framework.utils.FileUtils;
import com.bigfans.framework.utils.IOUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;

/**
 * 
 * @Title:
 * @Description: 七牛云存储
 * @author lichong
 * @date 2015年12月23日 上午9:33:07
 * @version V1.0
 */
public class QiniuFileStoragePlugin implements FileStoragePlugin {

	private static final String QRCODE_FORDER = "qrCode";
	private static final String PRODUCT_FORDER = "itemservice";
	private UploadManager uploadManager;

	private String accessKey;
	private String secretKey;
	private String bucketName;
	private String bucketHostName;

	public QiniuFileStoragePlugin(String accessKey, String secretKey, String bucketName, String bucketHostName) {
		this.accessKey = accessKey;
		this.secretKey = secretKey;
		this.bucketName = bucketName;
		this.bucketHostName = bucketHostName;
		this.uploadManager = new UploadManager();
	}

	@Override
	public String getStorageType() {
		return "qiniu";
	}

	@Override
	public boolean fileExists(String path) {
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth);
		try {
			FileInfo stat = bucketManager.stat(bucketName, path);
			return stat != null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public UploadResult upload(File srcFile, String target) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(srcFile);
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
		return this.uploadFile(fis, target);
	}
	
	@Override
	public File download(String fileName) {
		String destName = fileName.substring(fileName.lastIndexOf("/") + 1);
		File dest = FileUtils.newTempFile(destName);
		try {
			String encodedFileName = URLEncoder.encode(fileName, "utf-8");
			String finalUrl = String.format("%s/%s", bucketHostName, encodedFileName);
			System.out.println(finalUrl);
			URL url = new URL(finalUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();
			IOUtils.copyToFile(is, dest);
		} catch (Exception e) {
			dest.deleteOnExit();
			e.printStackTrace();
			throw new RuntimeException("下载文件失败");
		}
		return dest;
	}
	
	public UploadResult uploadFile(InputStream is, String target) {
		
		UploadResult result = new UploadResult();
		Auth auth = Auth.create(accessKey, secretKey);
		String token = auth.uploadToken(bucketName);
		try {
			byte[] byteData = IOUtils.toByteArray(is);
			Response response = uploadManager.put(byteData, target, token, null, null, false);
			//解析上传成功的结果
	        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			if(response.isOK()){
				result.setSuccess(true);
				result.setFilePath(bucketHostName + "/" + putRet.key);
				result.setStorageType(getStorageType());
				result.setFileKey(target);
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(is);
		}
		return result;
	}
	
	public UploadResult listFiles(String path){
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth);
		BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucketName, path);
		while (fileListIterator.hasNext()) {
		    //处理获取的file list结果
		    FileInfo[] items = fileListIterator.next();
		    for (FileInfo item : items) {
		        System.out.println(item.key);
		        System.out.println(item.hash);
		        System.out.println(item.fsize);
		        System.out.println(item.mimeType);
		        System.out.println(item.putTime);
		        System.out.println(item.endUser);
		    }
		}
		return null;
	}
	
	public UploadResult deleteFile(String targetFile){
		Auth auth = Auth.create(accessKey, secretKey);
		BucketManager bucketManager = new BucketManager(auth);
		try {
		    bucketManager.delete(bucketName, targetFile);
		} catch (QiniuException ex) {
		    //如果遇到异常，说明删除失败
		    System.err.println(ex.code());
		    System.err.println(ex.response.toString());
		}
		
		UploadResult res = new UploadResult();
		res.setSuccess(true);
		return res;
	}

	@Override
	public void plugin() {
		uploadManager = new UploadManager();
//		threadPool = Executors.newFixedThreadPool(20);
	}

	@Override
	public void unplugin() {

	}

	@Override
	public UploadResult uploadQrCodeImg(File srcFile, String orderNo) {
		return this.upload(srcFile, QRCODE_FORDER + "/" + orderNo + "/" + srcFile.getName());
	}
	
	@Override
	public UploadResult uploadProductImg(File srcFile, String prodId){
		return this.upload(srcFile, PRODUCT_FORDER + "/" + prodId + "/" + srcFile.getName());
	}
}
